<?php

namespace App\Http\Controllers\Wechat;

use App\Http\Controllers\Controller;
use App\Http\Requests\CashAdd;
use App\Models\Cash;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;


class CashController extends Controller
{
    // 提现列表
    public function index(Request $request)
    {
        $model = Cash::whereUserId(auth('wechat')->id())->orderByDesc('id');

        // 搜索
        $start_date = $request->post('start_date'); // 2021-04-20 01:00:00
        $end_date = $request->post('end_date'); // 2021-04-21 23:59:59
        if ($start_date && $end_date) {
            if ($start_date == $end_date) {
                $model->whereDate('created_at', $start_date);
            } else {
                $model->where('created_at', '>=', $start_date)
                    ->where('created_at', '<=', $end_date);
            }
        }

        $result = $model->paginate($this->limit);
        return $this->writeJson(0, $result->items());
    }

    // 增加提现
    public function add(CashAdd $request)
    {
        $money = $request->post('money');
        $type = $request->post('type');
        $type_name = $request->post('type_name');
        $account = $request->post('account');
        $user = User::find(auth('wechat')->id());
        if ($money > $user->balance) {
            return $this->writeJson(500, null, '余额不足');
        }

        try {
            DB::beginTransaction();
            $model = new Cash();
            $model->user_id = $user->id;
            $model->money = $money;
            $model->type = $type;
            $model->type_name = $type_name;
            $model->account = $account;
            $model->save();

            // 扣除余额
            User::whereId($user->id)->decrement('balance', $money);

            DB::commit();
            return $this->writeJson(0, null, '提交成功');
        } catch (\Exception $exception) {
            DB::rollBack();
            \Log::error($exception);
        } catch (\Throwable $e) {
            DB::rollBack();
            \Log::error($e);
        }
        return $this->writeJson(500, null, '提现失败');
    }
}
